extends Area2D

enum State {INIT,DOWN}
var state = State.INIT
var level
var is_shadow = false
var selected_type = "sunFlower"
var shooting = false
var blood = 100
var bullet = preload("res://scenes/bullet.tscn")
var field_slice
var shootable_types = [
	"peaShooter",
]

func _ready():
	pass
	
func _input(event):
	if event is InputEventMouseMotion:
		if state == State.INIT :
			if is_shadow == false: #不是影子，则跟随鼠标
				position = event.position
			else:
				field_slice = level.calc_shadow_position(event.position) #是影子，则计算当前位置对应的格子坐标
				position = (level.field_slices[field_slice.x][field_slice.y][0] +  
								level.field_slices[field_slice.x][field_slice.y][1])/2  #计算该格子的中心位置
					
	elif event is InputEventMouseButton:
		if event.button_index == MOUSE_BUTTON_LEFT and event.pressed:
			if is_shadow:
				queue_free()
			else:
				if state == State.INIT:
					field_slice = level.calc_shadow_position(event.position) #当鼠标点击，如果不是影子，则移动到对应格子的中心
					state = State.DOWN
					level.append_plant(field_slice,self)
					$AnimatedSprite2D.play(selected_type) #开始播放动画

# 这个函数用于控制造型在开始加入场景时，停留在第一帧。
func show_moving_anim():
	$AnimatedSprite2D.play(selected_type)
	$AnimatedSprite2D.stop()
	$AnimatedSprite2D.frame = 0

func _on_area_entered(area: Area2D) -> void:
	$UnderAttackTimer.start()

func _on_timer_timeout() -> void:
	blood -= 20
	if blood <= 0:
		level.remove_plant(field_slice)

func _on_area_exited(area: Area2D) -> void:
	$UnderAttackTimer.stop()

func start_attack():
	print("ready to attack %s"%selected_type)
	if selected_type in shootable_types and $AttackTimer.is_stopped():
		print("Plant %s start attack"%(field_slice))
		$AttackTimer.start()

func stop_attack():
	if not $AttackTimer.is_stopped():
		print("Plant %s stop attack"%(field_slice))
		$AttackTimer.stop()

func _on_attack_timer_timeout() -> void:
	var new_bullet = bullet.instantiate()
	new_bullet.position = position + Vector2(40,-18)
	level.add_child(new_bullet)
	
